package com.tanchengjin.admin.modules.blog.controller;

import com.github.pagehelper.PageInfo;
import com.tanchengjin.admin.modules.blog.service.ArticleService;
import com.tanchengjin.admin.modules.blog.service.CategoryService;
import com.tanchengjin.admin.modules.cms.mapper.ArticleMapper;
import com.tanchengjin.admin.modules.cms.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
public class IndexController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private LocaleResolver localeResolver;


    @GetMapping("")
    public String index(Model model, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size, @RequestParam(required = false) String q) {
        PageInfo<Article> articleList = new PageInfo<>();
        articleList = articleService.getArticleListByPagination(page, size);
        model.addAttribute("articleList", articleList);
        return "/index/index";
    }


    @RequestMapping("/language/{lang}")
    public String setLanguage(@PathVariable("lang") String lang, HttpServletRequest request, HttpServletResponse response) {
        Locale locale = null;

        int ps = lang.indexOf("_");
        if (ps > 0) {
            String language = lang.substring(0, ps);
            String country = lang.substring(ps + 1);
            locale = new Locale(language, country);
        } else {
            locale = new Locale("zn", "CN");
        }

        localeResolver.setLocale(request, response, locale);
        String referer = request.getHeader("Referer");
        return "redirect:" + (referer == null ? "/" : referer);
    }
}
